<!-- 登录页面 -->
<template>
	<div>
		<div class="login">
			<div class="login-part">
				<div class="call-back-icon">
					<el-tooltip class="item" effect="light" content="返回主页" placement="top">
						<i class="el-icon-sunny my-el-icon" @click="callBackhome"></i>
					</el-tooltip>
					<el-tooltip class="item" effect="light" content="前往注册" placement="top">
						<i class="el-icon-cloudy my-el-icon" @click="goToRegister"></i>
					</el-tooltip>
				</div>
				<div class="from-box">
					<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
						class="demo-ruleForm">
						<el-form-item prop="userName">
							<el-input type="text" placeholder="昵称(2~10位)" v-model="ruleForm.userName" maxlength="10"
								minlength="2" show-word-limit clearable></el-input>
						</el-form-item>
						<el-form-item prop="pass">
							<el-input type="password" placeholder="密码" v-model="ruleForm.pass" autocomplete="off"
								clearable>
							</el-input>
						</el-form-item>
						<el-form-item prop="verifycode">
							<el-input placeholder="请输入图片验证码" v-model="ruleForm.verifycode"></el-input>
							<div @click="refreshCode" class="identify-span">
								<s-identify :identifyCode="identifyCode"></s-identify>
							</div>

						</el-form-item>
						<div class="from-butn-box">
							<el-form-item>
								<el-button class="from-butn" type="primary" @click="submitForm('ruleForm')">登录
								</el-button>
								<el-button class="from-butn" @click="resetForm('ruleForm')">重置</el-button>
							</el-form-item>
						</div>

					</el-form>
				</div>




			</div>
		</div>

	</div>
</template>

<script>
	// 引入图片验证码组件
	import SIdentify from '../identify/SIdentify.vue'
	import {
		devUserManagementUrl
	} from '@/api/apiconst'
	
	import jwtDecode from 'jwt-decode'
 import {global} from '@/utils/constants'
	
	export default {
		name: "Login",
		components: {
			SIdentify
		},
		mounted() {
			// 验证码初始化
			this.identifyCode = ''
			this.makeCode(this.identifyCodes, 4)
		},

		data() {
			//校验用户名
			var validateUserName = (rule, value, callback) => {

				if (!value) {
					return callback(new Error('昵称不能为空'));
				} else if (value.length >= 2 && value.length <= 10) {
					callback();
				} else {

					return callback(new Error('昵称需要2~10个字符'));
				}

			};

			//校验密码
			var validatePass = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入密码'));
				} else {
					if (this.ruleForm.checkPass !== '') {
						this.$refs.ruleForm.validateField('checkPass');
					}
					callback();
				}
			};


			// 验证码自定义验证规则
			const verificationCode = (rule, value, callback) => {
				// console.log("shuju--->","222".toLowerCase());
				const strValue = value + "";
				console.log(value)
				const newVal = strValue.toLowerCase()
				const identifyStr = this.identifyCode.toLowerCase()
				if (newVal === '') {
					callback(new Error('请输入验证码'))
				} else if (newVal !== identifyStr) {
					console.log('validateVerifycode:', strValue)
					callback(new Error('验证码不正确!'))
					//刷新图形验证码
					this.refreshCode();
				} else {
					callback()
				}
			}



			return {
				identifyCode: "",
				identifyCodes: "0123456789abcdwerwshdjeJKDHRJHKOOPLMKQ", //绘制的随机数

				ruleForm: {
					userName: "",
					pass: '',
					verifycode: ""
				},
				rules: {
					userName: [{
						validator: validateUserName,
						trigger: 'blur'
					}],
					pass: [{
						validator: validatePass,
						trigger: 'blur'
					}],
					verifycode: [{
						validator: verificationCode,
						trigger: 'blur'

					}]
				}
			}

		},
		created() {
			this.refreshCode()
		},
		methods: {
			//返回主页
			callBackhome() {
				//跳转到主界面
				this.$router.push({
					path: "/home"
				});
			},
			goToRegister() {
				//跳转到注册界面
				this.$router.push({
					path: "/register"
				});
			},
			//点击提交按钮的逻辑
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
							if (valid) {
								console.log("收集到的数据22", this.ruleForm)
								this.$axios({
										method: 'POST', 
										url: '/user/login', 
										baseURL: devUserManagementUrl,
										data: {
											nickName: this.ruleForm.userName,
											password: this.ruleForm.pass
										}
										}
									).then(
										response => { //此处接收响应回来的数据
										console.log("登录数据",response)
											if(response.data.code==200){
												//存储token
												localStorage.setItem("token",response.data.data)
												 global.token = response.data.data // 赋值给全局变量
												const decode =  jwtDecode(response.data.data);
												console.log("登录解析的数据--》》",decode);
											
												//跳转到主页界面
												this.$router.push({
													path: "/home"
												});
												//刷新一次，使其连接ws
												window.location.reload();
											
											}else if (response.data.code == 5004) {
												this.$message.error('用户昵称或密码错误');
												//刷新图形验证码
												this.refreshCode();
											}
											
											
										},
										error => {
											this.$message.error('诶呀，服务器走丢了，稍后再来试试吧');
											//刷新图形验证码
											this.refreshCode();
										}
									);

								}
								else {
									return false;
								}
							});
					},
					//清除按钮逻辑
					resetForm(formName) {
						this.$refs[formName].resetFields();
					},

					refreshCode() {
						
						this.identifyCode = "";
						this.makeCode(this.identifyCodes, 4);
					},
					randomNum(min, max) {
						max = max + 1
						return Math.floor(Math.random() * (max - min) + min)
					},
					// 随机生成验证码字符串
					makeCode(data, len) {
						for (let i = 0; i < len; i++) {
							this.identifyCode += data[this.randomNum(0, data.length - 1)]
						}
					}


			}
		}
</script>

<style scoped>
	.from-butn-box {
		margin-top: 52px
	}

	.from-butn-box .from-butn {
		margin-right: 20px;
	}

	.identify-span {
		width: 90px;
		height: 30px;
		position: absolute;
		right: 30px;
		margin-top: 5px;
	}

	.s-canvas {
		width: 20px;
		height: 30px;
	}

	.my-el-icon {
		color: white;
		margin-right: 20px;
	}

	.from-box {
		width: 290px;
	}

	.login {
		background: url("@/assets/images/login-background-map.jpg");
		width: 100%;
		height: 100%;
		position: fixed;
		background-size: 100% 100%;
		left: 0;


	}

	.login-part {
		height: auto;
		opacity: 1.5;
		padding: 0px;
		max-width: 390px;
		margin: 170px auto;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.login-part .call-back-icon {
		text-align: center;
		font-size: 26px;
		padding-top: 17px;
		margin-bottom: 21px;
		height: 20px;
	}
</style>
